import * as React from "react";
import * as echarts from 'echarts';
import './index.scss';
import * as moment from 'moment';
import { Link } from "react-router-dom";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Spin, Progress, Tabs, Table,ConfigProvider } from 'antd';
import { CAMLFilter, CAMLCompare, CamlQuery, SPDataType, CamlParam, CamlOrderBy } from './../../config/CAMLHelper';
import { ListGUID } from '../../config/ListGuid';
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
import store from '../../store/index'
import Api from '../../config/api';
import zhCN from 'antd/es/locale/zh_CN';
import { dynamicsService } from '../../../../../services/services'
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Column } = Table;
import { ColumnProps } from 'antd/es/table';
const dateFormat = 'YYYY/MM/DD';
const colorArr = []
interface camlProp {
  params: CamlParam[],
  params1: CamlParam[]
}


const columns: ColumnProps<any>[] = [
  {
    title: '合同编号',
    dataIndex: 'Title',
    key: 'Title',
    align: 'left',
    width: '180px'
  },
  {
    title: '件名',
    dataIndex: 'filename',
    key: 'filename',
    align: 'left',
    render(text, record, index) {
      return (record.filename)
    },
  },
  {
    title: '对方公司名称',
    dataIndex: 'company_name',
    key: 'company_name',
    align: 'left',
  },
  {
    title: '到期时间',
    dataIndex: 'expire_date',
    key: 'expire_date',
    align: 'left',
    render(text, record, index) {
      return record.expire_date ? moment(record.expire_date).format('YYYY-MM-DD HH:mm:ss') : ''
    },
  },
  {
    title: '申请人',
    dataIndex: 'apply_user_nm',
    key: 'apply_user_nm',
    align: 'left',
  },
  {
    title: '附件',
    dataIndex: 'file',
    key: 'file',
    align: 'left',
    render: relative => (
      <div>
        {relative && relative.map(tag => {
          const dispUrl = ListGUID.DocumentLink;
          const splitName = tag.Name.split('.');
          return (
            <div key={tag.UniqueId}>
              {
                splitName[splitName.length - 1] === 'xlsx' ||splitName[splitName.length - 1] === 'xlsx' || splitName[splitName.length - 1] === 'xls' || splitName[splitName.length - 1] === 'docx' || splitName[splitName.length - 1] === 'doc' ? <a href={dispUrl + '?sourcedoc=' + tag.UniqueId} target="_blank">{tag.Name}</a> : <a href={tag.ServerRelativeUrl} download={tag.Name} target="_blank">{tag.Name}</a>
              }
            </div>
          );
        })}
      </div>
    ),
  },
];
export default class MinisterDashboard extends React.Component<any> {
  state = {
    filter: [],
    percent: 0,
    currentIndex: 0,
    dataCount: [],
    deptArr: [],
    currentDept: '',
    defaultActiveKey: '',
    data: [],
    pager: {
      current: 1,
      size: 10
    },
    loading: false,
    total: 0
  }

  public render(): React.ReactElement {
    return (
      <div className='minister-body'>
        <div className="title">
          <div className="chart-title">
            合同数据统计
          </div>
          <div className="line"></div>
        </div>
        <div className="progress-box">
          {
            this.state.dataCount.map((i, index) => {
              return (
                <div>
                  <Progress type="dashboard" strokeColor={index === 0 ? '#3396EE' : index === 1 ? '#80E124' : '#EC9E21'} width={150} percent={(i.value / 500) * 100} gapDegree={140} format={() => <div className="progress-text"><span>{i.value}</span>/{i.Total}</div>} />
                  <div className={['describe', index === this.state.currentIndex ? 'active' : ''].join(' ')} onClick={() => this.onDescribeChange(i, index)}>
                    {i.label}
                  </div>
                </div>
              )

            })
          }

          {/* <div>
            <Progress type="dashboard" strokeColor="#80E124" width={150} percent={this.state.percent} gapDegree={140} format={() => <div className="progress-text"><span>50</span>/200</div>}/>
            <div className="describe">
              本月到期合同申请书
            </div>
          </div>
          <div>
            <Progress type="dashboard" strokeColor="#EC9E21" width={150} percent={this.state.percent} gapDegree={140} format={() => <div className="progress-text"><span>50</span>/200</div>}/>
            <div className="describe">
              本月新增规章申请书
            </div>
          </div> */}
        </div>
        {
          this.state.deptArr.length > 0 && <div className="contract-tab">

            <Tabs defaultActiveKey={this.state.defaultActiveKey} onChange={(item) => this.setState({ defaultActiveKey: item, }, () => this.getTableData())}>
              {
                this.state.deptArr.map((i, index) => {
                  return (
                    <TabPane tab={i} key={i}>
                      <ConfigProvider locale={zhCN}>
                          <Table dataSource={this.state.data} columns={columns} loading={this.state.loading} pagination={{
                            // onChange: this.ontab.bind(this),
                            hideOnSinglePage: false,
                            total: this.state.total,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            defaultCurrent: 1,
                            current: this.state.pager.current,
                            pageSize: this.state.pager.size,
                            onShowSizeChange: (page, pageSize?) => {
                              this.setState({
                                pager: {
                                  current: page,
                                  size: pageSize
                                }
                              }, () => this.getTableData())
                            },
                            onChange: (page, pageSize?) => {
                              this.setState({
                                pager: {
                                  current: page,
                                  size: pageSize
                                }
                              }, () => {
                                this.getTableData()
                              })
                            },
                            showTotal: function (total) {
                              return `总共有 ${total} 条数据`;
                            }
                          }} />
                      </ConfigProvider>
                      
                    </TabPane>
                  )
                })
              }
              
            </Tabs>
          </div>
        }
        {
                  (!this.state.deptArr || this.state.deptArr.length === 0) && <ConfigProvider locale={zhCN}>
                  <Table dataSource={this.state.data} columns={columns} style={{marginTop: '30px'}} loading={this.state.loading} pagination={{
                        // onChange: this.ontab.bind(this),
                        hideOnSinglePage: false,
                        total: this.state.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        defaultCurrent: 1,
                        current: this.state.pager.current,
                        pageSize: this.state.pager.size,
                        onShowSizeChange: (page, pageSize?) => {
                          this.setState({
                            pager: {
                              current: page,
                              size: pageSize
                            }
                          }, () => this.getTableData())
                        },
                        onChange: (page, pageSize?) => {
                          this.setState({
                            pager: {
                              current: page,
                              size: pageSize
                            }
                          }, () => {
                            this.getTableData()
                          })
                        },
                        showTotal: function (total) {
                          return `总共有 ${total} 条数据`;
                        }
                      }} />
                  </ConfigProvider>
                }
      </div>

    );
  }
  getTableData = async () => {
    this.setState({
      loading: true,
      data: [],
    })
    let filter = JSON.parse(JSON.stringify(this.state.filter))
    if(this.state.defaultActiveKey !== '不明部门') {
      filter[0].where.push({
        key: 'sosiki_nm',
        filterType: "Eq",
        value: this.state.defaultActiveKey
      })
    } else {
      filter.push({
        logic: "and",
        where: [
        {
          key: 'sosiki_nm',
          filterType: "sosiki_nmEmpty",
          value: ''
        }] 
      })
    }
    
    let data = await Api._getPaged({
      Guid: this.state.currentIndex === 2 ? [ListGUID.Petition,'RegularMonth'] : [ListGUID.Petition,'PetitionMonth'],
      PageSize: this.state.pager.size,
      PageIndex: this.state.pager.current,
      FilterL: filter
    });
    for (let i = 0; i < data.data.length; i++) {
      if (data.data[i].SRUrls) {
        let index = data.data[i].SRUrls.indexOf("/")
        data.data[i].SRUrls = data.data[i].SRUrls.substring(index);
        let file = await Api.getFiles((this.state.currentIndex === 2  ? ListGUID.RegulationsPetitionLibRelativeUrl : ListGUID.ContractPetitionLibRelativeUrl)  + '/' + data.data[i].SRUrls + '/');
        data.data[i].file = file
      } else {
        let file = []
        data.data[i].file = file
      }
    }
    this.setState({
      data: data.data || [],
      total: data.Total || 0,
      loading: false
    })
    
  }
  onDescribeChange = (i, index) => {
    this.setState({
      data: [],
      loading: true
    })
    let filter = [
      {
        logic: "and",
        where: []
      }
    ];
    if (index === 1) {
      let firstDate = moment(new Date()).startOf('month').format('YYYY-MM-DD')
      let endtDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      filter[0].where.push(
        {
          key: 'expire_date',
          filterType: "Ge",
          value: `${firstDate} 00:00:00`
        },
        {
          key: 'expire_date',
          filterType: "Le",
          value: `${endtDate}`
        },
        {
          key: 'ItemBelong',
          filterType: "Eq",
          value: `0`
        }
      )
    } else {
      let firstDate = moment(new Date()).startOf('month').format('YYYY-MM-DD')
      let endtDate = moment(new Date()).endOf('month').format('YYYY-MM-DD')
      filter[0].where.push(
        {
          key: 'create_date',
          filterType: "Ge",
          value: `${firstDate} 00:00:00`
        },
        {
          key: 'create_date',
          filterType: "Le",
          value: `${endtDate} 23:59:59`
        },
        {
          key: 'ItemBelong',
          filterType: "Eq",
          value: `${index === 0 ? 0 : 1}`
        }
      )
    }
    
    this.setState({ deptArr: i.data, currentIndex: index, filter, defaultActiveKey: i.data.length > 0 ? i.data[0] : '' }, () => this.getTableData())
  }
  componentDidMount() {
    
    this.setState({
      dataCount: this.props.datacount || [],
      deptArr: this.props.datacount.length > 0 ? this.props.datacount[0].data : []
    }, () => {
      if (this.props.datacount.length > 0) {
        this.onDescribeChange(this.props.datacount[0], 0)
      }
    })

  }
  componentWillReceiveProps(nextProps: Readonly<any>, nextContext: any): void {
    this.setState({
      dataCount: nextProps.datacount || [],
      deptArr: nextProps.datacount.length > 0 ? nextProps.datacount[0].data : []
    }, () => {
      if (nextProps.datacount.length > 0) {
        this.onDescribeChange(nextProps.datacount[0], 0)
      }
    })
    
  }
}
